/* eslint-disable vue/no-parsing-error */
<!--
 * @Author: Lizhenyu
 * @Date: 2021-07-09 16:36:51
 * @FilePath: \usp-osm-frondend\src\views\serviceCenter\serviceProvider\updateProvider.vue
-->
<template>
  <div class="source" v-loading="pageLoading" :element-loading-text="loadingText">
    <div class="newPageTitle">
      <span class="backIcon" @click="closeDrawer"><i class="el-icon-back"></i></span>
      <h1 v-if="type === 'detail'" style="display:inline-block;margin-left:10px">
        详情
      </h1>
      <h1 v-else-if="type === 'add'" style="display:inline-block;margin-left:10px">
        添加服务商
      </h1>
      <h1 v-else style="display:inline-block;margin-left:10px">
        修改服务商
      </h1>
    </div>
    <el-form
      :model="editData"
      :rules="rules"
      label-position="left"
      ref="editAttribute"
      label-width="150px"
      size="small"
      class="dialogForm"
    >
      <el-form-item :prop="isAdd ? 'code' : ''" class="formPosition" label="服务商编号">
        <el-input
          type="text"
          v-model="editData.code"
          :disabled="true"
          maxlength="10"
          @input="editData.code=editData.code.replace(/[^\a-\z\A-\Z0-9\40]/g,'')"
          placeholder="服务商编号"
        ></el-input>
      </el-form-item>
      <el-form-item prop="name" class="formPosition" label="服务商名称">
        <el-input
          type="text"
          v-model="editData.name"
          :disabled="type === 'detail'"
          @input="editData.name=editData.name.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,'')"
          placeholder="服务商名称"
        ></el-input>
      </el-form-item>
      <el-form-item prop="type" class="formPosition" label="服务商类型">
        <el-select
          v-model="editData.type"
          :disabled="!isAdd"
          placeholder="服务商类型"
        >
          <el-option
            v-for="item in lookupItems.SERVICESTYPE"
            :key="item.id"
            :label="item.dicName"
            :value="item.dicCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="contactUser" class="formPosition" label="联系人">
        <el-input
          type="text"
          v-model="editData.contactUser"
          :disabled="type === 'detail'"
          @input="editData.contactUser=editData.contactUser.replace(inputVaildate,'')"
          placeholder="联系人"
        ></el-input>
      </el-form-item>
      <el-form-item prop="contactPhone" class="formPosition" label="联系电话">
        <el-input
          type="number"
          :disabled="type === 'detail'"
          v-model="editData.contactPhone"
          placeholder="联系电话"
        ></el-input>
      </el-form-item>
      <el-form-item prop="contactEmail" class="formPosition" label="联系邮箱">
        <el-input
          type="text"
          :disabled="type === 'detail'"
          v-model="editData.contactEmail"
          placeholder="联系邮箱"
        ></el-input>
      </el-form-item>
      <el-form-item prop="contactAddress" class="formPosition" label="地址">
        <el-input
          type="text"
          :disabled="type === 'detail'"
          v-model="editData.contactAddress"
          @input="editData.contactAddress=editData.contactAddress.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,'')"
          placeholder="地址"
        ></el-input>
      </el-form-item>
    </el-form>
    <div class="footer">
      <div v-if="type !== 'detail'" class="footer-btn">
        <el-button @click="closeDrawer" class="white-btn">取消</el-button>
        <el-button
          @click="saveEdit('editAttribute')"
          class="dark-btn"
        >保存</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { saveServiceProviderEdit, getServiceProviderDetail } from '@/api/service'
import { mapGetters } from 'vuex'
import { common } from '@/mixins/common'
import { setRouterParams, getRouterParams } from '@/utils/auth'

export default {
  name: 'updateProvider',
  mixins: [common],
  components: { },
  data () {
    var specialValidate = (rule, value, callback) => {
      // 特殊字符判断
      // eslint-disable-next-line
      var reg = /^(?=[0-9a-zA-Z\u4e00-\u9fa5\u00C0-\u00FF])[0-9a-zA-Z\s\u4e00-\u9fa5\d_+-./|:;'&%¿¡\*\(\)\u00C0-\u00FF]+$/i
      if (!reg.test(value)) {
        callback(this.$t('specialValidateMore'))
      } else {
        callback()
      }
    }
    return {
      id: '',
      pageLoading: false,
      isUpdateNum: 0,
      isAdd: true,
      type: '',
      loadingText: '加载中...',
      showNameRequire: false,
      inputVaildate: /[`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、0-9]/g,
      // desc: desc,
      dialogEdit: false,
      dialogTitle: '',
      tabsData: [],
      orderInfo: [],
      rules: {
        code: [
          {
            required: false,
            message: '服务商编号不能为空',
            trigger: 'blur'
          },
          { min: 10, max: 10, message: '必须是10位编码', trigger: 'blur' }
        ],
        name: [
          {
            required: true,
            message: '服务商名称不能为空',
            trigger: 'blur'
          },
          { validator: specialValidate, trigger: 'blur' }
        ],
        type: [
          {
            required: true,
            message: '请选择服务商的类型',
            trigger: 'blur'
          }
        ]
      },
      editData: {
        code: '',
        name: '',
        type: '',
        contactUser: '',
        contactPhone: '',
        contactEmail: '',
        contactAddress: '',
        status: ''
      },
      isSave: false
    }
  },
  mounted () {
    this.getUpdateChange()
  },
  created () {
    this.attributeAction(this.$route.params.id)
  },
  computed: {
    ...mapGetters(['lookupItems'])
  },
  beforeRouteLeave (to, from, next) {
    if (this.isSave) {
      next()
    } else {
      if (this.isUpdateNum > 1) {
        this.$confirm('确定离开此页面？如果离开，更改将丢失', '', {
          confirmButtonText: '确认',
          cancelButtonText: '取消'
        }).then(() => {
          next()
        }).catch(() => {
          next(false)
          this.$setMenuActived(this.$route.path)
        })
      } else {
        next()
      }
    }
  },
  methods: {
    getUpdateChange () {
      this.isUpdateNum = 0
      /* === 弹窗监听 start ==== */
      this.$watch('editData', function () {
        this.isUpdateNum++
      }, { deep: true })
      /* === 弹窗监听 end ==== */
    },
    saveEdit (formName) {
      // 保存新增修改
      const self = this
      this.isSave = true
      this.$refs[formName].validate(valid => {
        if (valid) {
          const data = self.editData
          // 默认为启用
          if (this.isAdd) {
            data.status = '1'
          }
          data.id = this.id
          saveServiceProviderEdit(data)
            .then(response => {
              // 调用接口保存新增修改attribute
              const data = response
              if (Number(data.code) === 1) {
                self.$emit('search')
                self.$alert('数据保存成功', {
                  confirmButtonText: '确定',
                  callback: action => {
                    this.$router.push({ name: 'serviceProvider' })
                  }
                })
              } else {
                this.$alert(data.msg)
              }
            })
            .catch(error => {
              this.$confirm(error, {
                confirmbuttontext: '确定',
                showcancelbutton: false
              })
            })
        } else {
          return false
        }
      })
    },
    closeDrawer () {
      this.$router.push({ name: 'serviceProvider' })
    },
    attributeAction (id) {
      const name = this.$route.name
      this.type = this.$route.params.type
      if (this.type === 'detail') {
        this.$route.meta.title = '详情'
        this.$route.meta.titlePath = '详情'
      } else if (this.type === 'edit') {
        this.$route.meta.title = '修改服务商'
        this.$route.meta.titlePath = '修改服务商'
      } else {
        this.$route.meta.title = '新增服务商'
        this.$route.meta.titlePath = '新增服务商'
      }
      if (id) {
        this.id = id
        this.isAdd = false
        setRouterParams(this.$route)
        this.edit(this.id)
      } else {
        if (name === 'editProvider') {
          this.isAdd = false
          const routeParams = getRouterParams(this.$route)
          this.id = routeParams.id
          this.type = routeParams.type
          this.edit(this.id)
        } else {
          setRouterParams(this.$route)
          this.isAdd = true
          this.type = 'add'
          this.initpage()
        }
      }
    },
    edit (id) {
      const self = this
      const model = { id: id }
      this.pageLoading = true
      getServiceProviderDetail(model)
        .then(response => {
          this.pageLoading = false
          const data = response
          if (data) {
            if (Number(data.code) === 1) {
              const obj = data.obj
              self.editData = obj
            } else if (Number(data.code) === 0) {
              this.$confirm(data.msg, {
                confirmButtonText: '确定',
                showCancelButton: false
              })
            } else {
              this.$confirm(data.code, {
                confirmButtonText: '确定',
                showCancelButton: false
              })
            }
          }
        })
        .catch(_ => {
          this.pageLoading = false
        })
    },
    initpage () {
      // 初始页面值
      this.editData = {
        code: '',
        name: '',
        type: '',
        contactUser: '',
        contactPhone: '',
        contactEmail: '',
        contactAddress: '',
        status: ''
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.langBox {
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 12px;
  text-align: center;
  padding: 2px 0px;
  width: 50px;
  float: left;
  margin-left: 10px;
  span {
    display: block;
    line-height: 12px;
  }
  .lang {
    border-bottom: 1px dashed #ccc;
  }
}
.dialogForm {
  .formPosition {
    position: relative;
  }
  .descSty {
    position: absolute;
    top: -152px;
    left: 115px;
  }
}
/deep/ .el-form--label-left .el-form-item__label {
  text-align: right;
  padding-right: 20px;
}
</style>
